import React,{useState} from 'react';
import { Button, Checkbox, Form, Input,message,Spin } from 'antd';
import *as api from "@/api/users"
import {connect} from "react-redux"
import userActionCreator from '@/store/actions/userAction';
import { useNavigate } from 'react-router-dom';
import loginStyle from "./login.module.css"
//将dispatch方法映射到组件内
const mapDispatchToProps=(dispatch:any)=>{
      return {
          setUserInfo(payload:any){
              dispatch(userActionCreator('SET_USERINFO',payload))
          }
      }
}
//校验规则

//校验用户名
const validatorUsername=(rules:any,value:string)=>{
     if(!value){
          return Promise.reject('请输入用户名')
     }
     //如果通过 返回Promise.resolve 如果不通过 返回Promise.reject
     if (value.length<3){
        return Promise.reject('用户名的长度不能少于3位')
     }else{
        return Promise.resolve()
     }
}
//校验密码
const validatorPassword=(rules:any,value:string)=>{
    if(!value){
         return Promise.reject('请输入密码')
    }
    //如果通过 返回Promise.resolve 如果不通过 返回Promise.reject
    if (value.length<3){
       return Promise.reject('密码的长度不能少于3位')
    }else{
       return Promise.resolve()
    }
}
//登入请求传递参数的类型
declare global{
    interface loginParam{
         username:string;
         password:string;
         remember:boolean
    }
}
const Login: React.FC<{setUserInfo?:(payload:any)=>void}> = (props) => {
  //控制加载动画
  let [loading,setLoading]=useState<boolean>(false)
  //使用自定义的本地存储
  // let tokenStorage=useStorage('qf-token')
  // let userInfoStorage=useStorage('user-info')
  // let permissionStorage=useStorage('btn-permission')
  //编程式导航hook
  let navigate=useNavigate()
    //表单校验通过,会回调这个onFinish
  const onFinish =async (values: loginParam) => {

    // console.log('Success:', values);
    //打开加载动画
    setLoading(true)
    //发起登入请求
    try{
      let res=await api.loginApi(values.username,values.password)
      //关闭加载动画
      setLoading(false)
      if(!res.data.state){
         //密码错误登入失败的情况
         message.open({
            type:'error',
            content:res.data.msg
         })
         //弹框提示
         return
      }
      // console.log(res)
      //存储token到sessionStorage
      sessionStorage.setItem('qf-token',res.data.token)
      //存储userInfo到redux
      props.setUserInfo!(res.data.userInfo)
      //页面进行跳转到主页
      navigate("/")
      message.open({
          type:'success',
          content:res.data.msg
      })
    }catch(e){
      console.log(e)
    }
  };
    //表单验证失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Spin spinning={loading} tip='正在载入' className={loginStyle['login-spin']}>
       <Form
      name="loginForm "
      labelCol={{ span: 2 }}
      wrapperCol={{ span: 5 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true,validator:validatorUsername }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true,validator:validatorPassword }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 2, span: 5 }}>
        <Checkbox>七天免登入</Checkbox>
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 2, span: 5 }}>
        <Button type="primary" htmlType="submit">
          登入
        </Button>
      </Form.Item>
    </Form>
    </Spin>
  );
};

export default connect(null,mapDispatchToProps)(Login)